package com.platform.api.bzproject.controller;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.platform.api.bzproject.model.*;
import com.platform.api.bzproject.service.*;
import com.platform.api.common.controller.BaseController;
import com.platform.common.core.Constant;
import com.platform.common.core.Result;
import com.platform.common.util.GenerateSequenceUtil;
import com.platform.security.util.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 * 余额记录表 前端控制器  不需要认证
 * </p>
 *-- 源码联系微信：2549789059
 * @author guoshao
 * @since 2021-10-29
 */
@RestController
@RequestMapping("{appid}/pbalance")
public class PBalanceRecordController extends BaseController {

    @Autowired
    private IBalanceRecordService iBalanceRecordService;

    @Autowired
    private BzBaseInfoService bzBaseInfoService;

    @Autowired
    private IBzTalentService iBzTalentService;


    @Autowired
    private BzAllWallpaperService bzAllWallpaperService;

    @Autowired
    private IDistributionProfitService iDistributionProfitService;

    @Autowired
    private IDownRecordService iDownRecordService;

    @Autowired
    private IBzDeductionRecordService iBzDeductionRecordService;


    @PostMapping("save")
    public Result save(@PathVariable String appid, @RequestBody BalanceRecord balanceRecord){

        balanceRecord.setPlatformType(getSystemType());

        Date date = new Date();

        BzBaseInfo baseInfo = bzBaseInfoService.getOne(new QueryWrapper<BzBaseInfo>().eq("appid", appid));

        int adCount = iDownRecordService.count(new QueryWrapper<DownRecord>().eq("user_id", balanceRecord.getSouUserId()));
        if(adCount >= baseInfo.getAdCount()){
            return Result.failure("当天观看次数达到上限");
        }

        //记录下载次数
        DownRecord downRecord = new DownRecord();
        downRecord.setCreateTime(date);
        downRecord.setUserId(balanceRecord.getSouUserId());
        iDownRecordService.save(downRecord);

        if(adCount >= baseInfo.getSaveCount()){
            return Result.failure("当天保存次数达到上限");
        }

        if(null == baseInfo){
            return Result.failure("小程序配置信息未找到");
        }
        if(1 != baseInfo.getDownProfit()){
            return Result.failure("下载收益未开启");
        }

        balanceRecord.setAppid(appid);
        balanceRecord.setSysData(1); //默认设置 1
        BzAllWallpaper wallpaper = bzAllWallpaperService.getById(balanceRecord.getWid());

        //保存下载记录
        bzAllWallpaperService.updateDownCount(wallpaper);
        if(StringUtils.isEmpty(wallpaper.getOpenid())){
            return Result.failure("获取用户信息失败");
        }

        balanceRecord.setUserId(wallpaper.getOpenid());

        //获取达人用户信息
        BzTalent talent = iBzTalentService.getOne(new QueryWrapper<BzTalent>().eq("userid", balanceRecord.getUserId()));
        if(null == talent){
            return Result.failure("获取达人信息失败");
        }

        balanceRecord.setCreateTime(date);
        balanceRecord.setMoney(null);
        balanceRecord.setStatus(1);
        balanceRecord.setSysData(0);
        boolean save = addBalance(balanceRecord,talent.getWord());

        if(save){
            if(StringUtils.isNotBlank(talent.getRecommenderWord())){
                //添加分销收益记录
                BzTalent user = iBzTalentService.getOne(new QueryWrapper<BzTalent>().eq("word", talent.getRecommenderWord()));
                DistributionProfit profit = new DistributionProfit();
                profit.setPlatformType(getSystemType());
                profit.setBid(balanceRecord.getId());
                profit.setStatus(1);
                profit.setUserId(user.getUserid());
                profit.setSouUserId(talent.getUserid());
                profit.setCreateTime(date);
                profit.setSource(1);
                profit.setAppid(appid);
                profit.setFlowNo(Constant.ORDER_YQ_NO_PREFIX + GenerateSequenceUtil.generateSequenceNo());
                iDistributionProfitService.save(profit);
            }
        }
        //新增或修改扣量信息,扣量
        iBzDeductionRecordService.saveOrUpdateDeductionRecord(talent.getParentUserid(),wallpaper.getOpenid(),0,true);

        iBzDeductionRecordService.deduction(wallpaper.getOpenid(),talent.getParentUserid(), appid);

        return Result.success(save);
    }

    public boolean addBalance(BalanceRecord balanceRecord,String word){
        balanceRecord.setCreateTime(new Date());

        if(StringUtils.isNotBlank(word)){
            //String no = Constant.ORDER_NO_PREFIX + word+ GenerateSequenceUtil.generateSequenceNo();
            String no = Constant.ORDER_NO_PREFIX + GenerateSequenceUtil.generateSequenceNo();
            balanceRecord.setFlowNo(no);
        }else{
            balanceRecord.setFlowNo(Constant.ORDER_SYS_NO_PREFIX + DateUtil.format(new Date(),"yyyyMMddHHmmsss"));
        }
        balanceRecord.setMoney(null);
        balanceRecord.setStatus(1);
        boolean save = iBalanceRecordService.save(balanceRecord);
        return save;
    }


}
